package com.yfbao.horizon.schedule.tk.sch;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Slf4j
@Component
public class CustomTaskSchedulerMonitor {

    private final ThreadPoolTaskScheduler taskScheduler;

    public CustomTaskSchedulerMonitor(ThreadPoolTaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @Autowired
    private ScheduledTaskInfo scheduledTaskInfo;

    private static int printNum=0;
    private static ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNamePrefix("schedule-Monitor-")
            .build();
    private ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1, threadFactory);

    @PostConstruct
    public void monitorTasks() {
//         Example: 添加监控任务
        ScheduledFuture<?> task = taskScheduler.schedule(() -> {
//            log.info("Executing monitored task...");
            if(printNum>3){
                return;
            }
            scheduledTaskInfo.printScheduledTasks();
            printNum++;
        }, new CronTrigger("0/30 * * * * *")); // 每5秒执行一次

        log.info("Task scheduled with CronTrigger: " + task);


        scheduler.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    //打印本地缓存统计信息
                  Thread.sleep(1000);
                } catch (Throwable t) {
                    log.error("do cacheStat error", t);
                }
            }
        }, 5, 10, TimeUnit.SECONDS);
    }
}
